<template>
  <div class="archived-contract-detail">
    <div class="header">
      <div class="header-content d-flex justify-content-between align-items-center">
        <h2>归档合同详情</h2>
        <button @click="goBack" class="btn btn-secondary">
          <i class="fa fa-arrow-left mr-2"></i>返回列表
        </button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-indicator">
      <div class="spinner"></div>
      <p>加载合同中...</p>
    </div>

    <!-- 错误消息 -->
    <div v-if="errorMessage" class="error-message">
      <div class="alert alert-danger">
        <i class="fa fa-exclamation-circle mr-2"></i>{{ errorMessage }}
      </div>
    </div>

    <div v-if="contract && !loading" class="card mt-4">
      <div class="card-body">
        <!-- 合同详情 - 上半部分 -->
        <h3 class="contract-name">{{ contract.name }}</h3>
        <div class="contract-info">
          <p><strong>合同ID:</strong> {{ contract.id }}</p>
          <p><strong>项目经理:</strong> {{ contract.projectManager?.name || '未指定' }}</p>
          <p><strong>客户:</strong> {{ contract.customer?.companyName || '未指定' }}</p>
          <p><strong>合同状态:</strong> 已归档</p>
          <p><strong>创建时间:</strong> {{ formatDate(contract.createTime) }}</p>
          <p><strong>归档时间:</strong> {{ formatDate(contract.updateTime) }}</p>
        </div>

        <!-- 进度条和里程碑计划 -->
        <div class="progress-section mt-4">
          <h4>合同进度</h4>
          <div class="progress">
            <div
                :class="['progress-bar', getProgressClass(milestoneStatus)]"
                :style="{ width: getProgressWidth(milestoneStatus) }"
            >
              {{ getProgressText(milestoneStatus) }} ({{ milestoneStatus * 25 }}%)
            </div>
          </div>
          <div class="progress-steps mt-3">
            <div class="step" :class="{ active: milestoneStatus >= 1 }">
              <div class="step-indicator">1</div>
              <div class="step-text">未开始</div>
            </div>
            <div class="progress-line" :class="{ active: milestoneStatus >= 2 }"></div>
            <div class="step" :class="{ active: milestoneStatus >= 2 }">
              <div class="step-indicator">2</div>
              <div class="step-text">定金阶段</div>
            </div>
            <div class="progress-line" :class="{ active: milestoneStatus >= 3 }"></div>
            <div class="step" :class="{ active: milestoneStatus >= 3 }">
              <div class="step-indicator">3</div>
              <div class="step-text">执行阶段</div>
            </div>
            <div class="progress-line" :class="{ active: milestoneStatus >= 4 }"></div>
            <div class="step" :class="{ active: milestoneStatus >= 4 }">
              <div class="step-indicator">4</div>
              <div class="step-text">已完成</div>
            </div>
          </div>

          <!-- 里程碑计划详情 -->
          <div class="milestone-plan mt-4">
            <h4>里程碑计划</h4>
            <div class="card">
              <div class="card-body">
                <div v-if="milestonePlan" class="plan-details">
                  <div class="form-group">
                    <label>定金阶段描述</label>
                    <p class="form-control-plaintext">{{ milestonePlan.depositStageDesc || '无描述' }}</p>
                  </div>
                  <div class="form-group">
                    <label>执行阶段描述</label>
                    <p class="form-control-plaintext">{{ milestonePlan.executionStageDesc || '无描述' }}</p>
                  </div>
                </div>
                <div v-else class="empty-message text-center py-2">
                  <i class="fa fa-info-circle text-muted mr-2"></i>暂无里程碑计划信息
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 合同条款 -->
        <div class="clauses-section mt-4">
          <h4>合同条款</h4>
          <div v-if="clauses.length > 0" class="clauses-list">
            <ul class="list-group">
              <li
                  v-for="clause in clauses"
                  :key="clause.id"
                  class="list-group-item"
              >
                <p class="mb-1"><strong>内容:</strong> {{ clause.content }}</p>
              </li>
            </ul>
          </div>
          <div v-else class="empty-message text-center py-2">
            <i class="fa fa-info-circle text-muted mr-2"></i>暂无条款
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

export default {
  name: 'EmployeeArchivedContractDetail',
  setup() {
    const route = useRoute()
    const router = useRouter()

    const contractId = ref(route.params.contractId)
    const contract = ref(null)
    const clauses = ref([])
    const milestonePlan = ref(null)
    const milestoneStatus = ref(1)
    const loading = ref(true)
    const errorMessage = ref('')

    // 进度状态映射
    const milestoneStatusMap = {
      1: "未开始",
      2: "定金阶段",
      3: "执行阶段",
      4: "已完成"
    }

    // 获取合同详情
    const fetchContractDetails = () => {
      loading.value = true
      errorMessage.value = ''

      if (!contractId.value) {
        errorMessage.value = '缺少合同ID参数'
        setTimeout(() => {
          router.push('/employee/archived-contracts')
        }, 2000)
        loading.value = false
        return
      }

      axios.get(`/auth/contracts/${contractId.value}`, {
        headers: {
          'X-Employee-Id': route.params.employeeId || ''
        }
      })
          .then(response => {
            console.log('获取归档合同详情成功:', response.data)
            contract.value = response.data
            // 归档合同的里程碑状态从合同对象获取
            milestoneStatus.value = contract.value.milestoneStatus || 1
          })
          .catch((err) => {
            console.error('获取归档合同详情失败', err)
            errorMessage.value = err.response?.data?.message || '获取合同详情失败，请重试'
          })
          .finally(() => {
            loading.value = false
          })
    }

    // 获取条款
    const fetchClauses = () => {
      if (!contractId.value) {
        console.log('合同ID不存在，无法获取条款')
        return
      }

      axios.get(`/auth/clauses/contract/${contractId.value}`)
          .then(response => {
            clauses.value = response.data
          })
          .catch((err) => {
            console.error('获取合同条款失败', err)
            errorMessage.value = '获取合同条款失败，请重试'
          })
    }

    // 获取里程碑计划
    const fetchMilestonePlan = () => {
      if (!contractId.value) {
        console.log('合同ID不存在，无法获取里程碑计划')
        return
      }

      axios.get(`/auth/milestone-plan/contract/${contractId.value}`)
          .then(response => {
            milestonePlan.value = response.data
            // 如有必要，更新里程碑状态
            if (response.data && response.data.status) {
              milestoneStatus.value = response.data.status
            }
          })
          .catch((err) => {
            console.error('获取里程碑计划失败', err)
            // 里程碑计划可能不存在，不设置错误信息
          })
    }

    // 返回上一级
    const goBack = () => {
      router.push('/employee/archived-contracts')
    }

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString()
    }

    // 获取进度条样式类
    const getProgressClass = (status) => {
      switch (status) {
        case 1: return 'bg-warning'
        case 2: return 'bg-info'
        case 3: return 'bg-primary'
        case 4: return 'bg-success'
        default: return 'bg-secondary'
      }
    }

    // 获取进度条宽度
    const getProgressWidth = (status) => {
      return status * 25 + '%'
    }

    // 获取进度文本
    const getProgressText = (status) => {
      return milestoneStatusMap[status] || `未知状态: ${status}`
    }

    onMounted(() => {
      fetchContractDetails()
      fetchClauses()
      fetchMilestonePlan()
    })

    return {
      contractId,
      contract,
      clauses,
      milestonePlan,
      milestoneStatus,
      loading,
      errorMessage,
      goBack,
      formatDate,
      getProgressClass,
      getProgressWidth,
      getProgressText
    }
  }
}
</script>

<style scoped>
.header {
  background-color: #f8f9fa;
  padding: 15px;
  border-bottom: 1px solid #dee2e6;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
}

.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border-top-color: #007bff;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.error-message {
  padding: 15px;
  color: #721c24;
  background-color: #f8d7da;
  border-radius: 4px;
  margin: 15px 0;
}

.contract-info {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
  margin-top: 20px;
}

.progress-section {
  margin-top: 30px;
}

.progress-steps {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  position: relative;
}

.progress-line {
  position: absolute;
  top: 15px;
  left: 30px;
  right: 30px;
  height: 2px;
  background-color: #e9ecef;
  z-index: 0;
}

.progress-line.active {
  background-color: #007bff;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 1;
}

.step-indicator {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #e9ecef;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-bottom: 5px;
}

.step.active .step-indicator {
  background-color: #007bff;
  color: white;
}

.milestone-plan {
  margin-top: 30px;
}

.clauses-section {
  margin-top: 30px;
}
</style>